#!/bin/bash

# 设置构建ID和应用参数
BUILD_ID=dontKillMe
APP_NAME="matrix_java-1.0.0.RELEASE.jar"
HEALTH_CHECK_URL="http://127.0.0.1:55055/actuator/health"
MAX_RETRIES=12
RETRY_DELAY=10

# 检查curl是否可用
if ! command -v curl &> /dev/null; then
    echo "Error: curl is required but not installed."
    exit 1
fi

# 获取java进程的pid
pid=$(pgrep -f "java.*$APP_NAME")

if [[ -n "$pid" ]]; then
    # 杀死java进程
    echo "Stopping existing application with PID: $pid"
    kill -9 "$pid"
    sleep 3
    # 确认进程已停止
    if ps -p $pid > /dev/null; then
        echo "Error: Failed to stop application with PID: $pid"
        exit 1
    fi
    echo "Application stopped successfully"
else
    echo "No existing application process found"
fi

# 检查JAR文件是否存在
if [[ ! -f "$APP_NAME" ]]; then
    echo "Error: JAR file $APP_NAME not found in current directory"
    exit 1
fi

# 设置启动参数
active="-Dspring.profiles.active=server_m"
JAVA_OPTS="-server -Xms55m -Xmx512m -Xss228k"

# 启动java应用
echo "Starting application: $APP_NAME"
BUILD_ID=DONTKILLME nohup java -jar $active "$APP_NAME" $JAVA_OPTS > log4mate.log 2>&1 &
APP_PID=$!

# 等待应用启动
echo "Waiting for application to start..."
for ((i = 0; i < MAX_RETRIES; i++)); do
    if curl -s "$HEALTH_CHECK_URL" > health_check.tmp; then
        state=$(grep -o '"status":[^,}]*' health_check.tmp | cut -d : -f 2 | tr -d ' "')
        if [[ "$state" == "UP" ]]; then
            echo "Application started successfully"
            rm -f health_check.tmp
            exit 0
        fi
    fi
    echo "Waiting for start (attempt $((i+1))/$MAX_RETRIES)..."
    sleep $RETRY_DELAY
done

# 获取启动失败的日志信息
ERROR_LOG=$(tail -n 20 log4mate.log)

# 清理临时文件
rm -f health_check.tmp

# 输出启动失败信息
echo "Error: Application failed to start after $((MAX_RETRIES * RETRY_DELAY)) seconds"
echo "Last 20 lines of log:"
echo "$ERROR_LOG"
exit 1
